package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupFormDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParams;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper,SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;
    /**
     *新增规格参数分组
     * @param bpdy
     */
    @Override
    public void insertGroup(SpecGroupFormDTO bpdy) {
        this.save(bpdy.toEntity(SpecGroup.class));
    }


    /**
     * 修改规格参数分组数据
     * @param body
     */
    @Override
    public void updateGroup(SpecGroupFormDTO body) {
        this.update(body.toEntity(SpecGroup.class),new QueryWrapper<SpecGroup>().eq("id",body.getId()));
    }

    /**
     * 根据商品分类id查询规格参数组的集合
     * @param cid 分类id
     * @return
     */
    @Override
    public List<SpecGroupFormDTO> selectSpeclistByCategoryId(Long cid) {
        return SpecGroupFormDTO.convertEntityList(this.query().eq("category_id",cid).list());
    }

    /**
     * 根据分类id查询规则组及组内参数
     * @param cid 分类id
     * @return
     */
    @Override
    public List<SpecGroupFormDTO> selctParamsByCategoryId(Long cid) {
        List<SpecGroupFormDTO> specGroupList = SpecGroupFormDTO.convertEntityList(this.query().eq("category_id",cid).list());

        // 查询规格参数
        List<SpecParamDTO> paramList = specParamService.selectParamsByConditions(cid, null, null);
        // 对规格参数分组，groupId一致的在一组
        Map<Long, List<SpecParamDTO>> map = paramList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 把参数放入group
        for (SpecGroupFormDTO groupDTO : specGroupList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return specGroupList;
    }
}
